package com.cong.cojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;
import com.cong.cojcodesandbox.mode.ExecuteCodeRequest;
import com.cong.cojcodesandbox.mode.ExecuteCodeResponse;
import com.cong.cojcodesandbox.mode.ExecuteMessage;
import com.cong.cojcodesandbox.mode.JudgeInfo;
import com.cong.cojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author 86188
 * @date 2023/09/05
 */
public class JavaNativeCodeSandboxOld implements CodeSandbox{

    public static final String GLOBAL_CODE_DIR_NAME = "tempCode";
    public static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    public static final String SECURITY_MANAGER_CLASS_NAME = "SandboxSecurityManager";

    public static final String SECURITY_MANAGER_PATH = "D:\\知识星球\\Coj-code-sandbox\\src\\main\\resources\\security";
    private static final List<String> blackList =  Arrays.asList("Files","exec");
    private static final long TIME_OUT =  5000L;
    public static final WordTree WORD_TREE;
    static {
        //初始化资源树
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(blackList);
    }
    public static void main(String[] args) {
        JavaNativeCodeSandboxOld javaNativeCodeSandbox = new JavaNativeCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
//        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/simpleCompute/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafeCode/SleepError.java", StandardCharsets.UTF_8);
        String code = ResourceUtil.readStr("testCode/unsafeCode/MemoryError.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafeCode/ReadFileError.java", StandardCharsets.UTF_8);
        executeCodeRequest.setInputList(Arrays.asList("1 2","1 3"));
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);

    }
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
//        System.setSecurityManager(new DenySecurityManager());

        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();
        //校验代码
        
//        FoundWord foundWord = WORD_TREE.matchWord(code);
//        if (foundWord!=null){
//            System.out.println("有敏感文件："+foundWord.getFoundWord());
//            return null;
//        }
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir+ File.separator + GLOBAL_CODE_DIR_NAME;
        //判断全局代码目录是否存在,没有则新建
        if (FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        Process compileProcess = null;
        try {
            compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (Exception e) {
            return getResponse(e);
        }
        //执行代码获取输出结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();

        for (String inputArg : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=utf-8 -cp %s;%s -Djava.security.manager=%s Main %s", userCodeParentPath,SECURITY_MANAGER_PATH,SECURITY_MANAGER_CLASS_NAME,SECURITY_MANAGER_CLASS_NAME, inputArg);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);;
                //超时控制
                new Thread(()->{
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时了，中断");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
//            ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(runCmd, "运行",inputArg);

                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                return getResponse(e);
            }


        }


        //收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        //取用时最大值，便于判断是否超时
        Long maxTime =0L;
        for (ExecuteMessage executeMessage : executeMessageList) {
            //错误信息不为空
            if (StrUtil.isNotBlank(executeMessage.getErrorMessage())){
                executeCodeResponse.setMessage(executeMessage.getErrorMessage());
                //用户提交代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time =  executeMessage.getTime();
            if (time != null){
                maxTime = Math.max(maxTime,time);
            }
        }
        //正常运行
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        //要用到第三方库十分麻烦 暂不实现
        //judgeInfo.setMemoryLimit();
        judgeInfo.setTime(maxTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        //文件清理 防止服务器空间不足
        if (userCodeFile.getParentFile() !=null){
            boolean result = FileUtil.del(userCodeParentPath);
            System.out.println("删除" +(result?"成功":"失败"));
        }

        return executeCodeResponse;
    }

    /**
     * 获取错误相应
     * @param throwable
     * @return
     */
    private ExecuteCodeResponse getResponse(Throwable throwable){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(throwable.getMessage());
        //代码沙箱执行错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
        
    }
}
